import axios from "axios";
import { ip, versionKey } from "@/api/config";
import router from '@/router'
import { Toast } from 'vant'

const request = axios.create({
    baseURL: ip,
    timeout:'5000s'
})

request.interceptors.request.use(config=>{
    if(localStorage.getItem('token')){
        config.headers['token'] = `${localStorage.getItem('token')}`
    }
    config.headers['versionKey'] = versionKey
    return config;
})

request.interceptors.response.use(res=>{
    if(res.headers['token']){
        localStorage.setItem('token', res.headers['token'])
    }
    if(res.data.code == 403){
        localStorage.removeItem('token')
        router.replace('/login').catch(()=>{})
    }
    // if(res.headers['Content-Type'] == 'application/json; charset=UTF-8'){
        if(res.data.code != 200 && res.data.code != 410){
            Toast(res.data.msg)
        }
    // }
    return res.data;
},
err=>{
    if(err.response.status == 403){
        Toast("当网络已被禁用")
    }else if(err.response.status == 404){

    }else{
        Toast("网络异常")
    }
    return Promise.reject(new Error(err))
})

export default request;